#include "hf_object_tracking.h"

HF_Object_Tracking::HF_Object_Tracking(QWidget *parent)
    : CommonGraphicsView{parent}
{
    this->setWindowTitle("稠密光流对象跟踪");
    QPushButton *btn = new QPushButton(this);
    btn->setText("选择视频");
    connect(btn,&QPushButton::clicked,[=](){
        choiceVideo();
    });
}


void HF_Object_Tracking::choiceVideo(){
    path = QFileDialog::getOpenFileName(this,"请选择视频","/Users/yangwei/Downloads/",tr("Image Files(*.mp4 *.avi)"));
    qDebug()<<"视频路径："<<path;
    hfObjectTracking(path.toStdString().c_str());
}

void HF_Object_Tracking::hfObjectTracking(const char* filePath){
    VideoCapture capture;
    capture.open(filePath);
    if(!capture.isOpened()){
        qDebug()<<"视频路径为空";
        return;
    }
    Mat frame,gray;
    Mat prev_frame ,prev_gray;
    Mat flowResult,flowData;
    capture.read(frame);//读取第一帧数据
    //转灰度图
    cvtColor(frame,prev_gray,COLOR_BGR2GRAY);//将frame转灰度图赋值给前一帧

    while(capture.read(frame)){
        cvtColor(frame,gray,COLOR_BGR2GRAY);
        if(!prev_gray.empty()){
            //稠密光流跟踪
            calcOpticalFlowFarneback(prev_gray,gray,flowData, 0.5, 3, 15, 3, 5, 1.2, 0);
            cvtColor(prev_gray, flowResult, COLOR_GRAY2BGR);
            for (int row = 0; row < flowResult.rows; row++) {
                for (int col = 0; col < flowResult.cols; col++) {
                    const Point2f fxy = flowData.at<Point2f>(row, col);
                    if (fxy.x > 1 || fxy.y > 1) {
                        line(flowResult, Point(col, row), Point(cvRound(col + fxy.x), cvRound(row + fxy.y)), Scalar(0, 255, 0), 2, 8, 0);
                        circle(flowResult, Point(col, row), 2, Scalar(0, 0, 255), -1);
                    }
                }
            }
            imshow("flow", flowResult);
            imshow("input", frame);
        }
//        imshow("frame",frame);
        int key = waitKey(1);
        if(key==27){
            break;
        }
    }

}
